package middle;

public class Solution_19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        int count = 0;
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        if (count == n) {
            return head.next;
        }
        node = head;
        for (int i = 1; i < count - n; i++) {
            node = node.next;
        }
        node.next = node.next.next;
        return head;
    }

    public static void main(String[] args) {
        Solution_19 model = new Solution_19();
        ListNode header = new ListNode(1);
        header.next = new ListNode(2);
        header.next.next = new ListNode(3);
        header.next.next.next = new ListNode(4);
        header.next.next.next.next = new ListNode(5);
        ListNode node = model.removeNthFromEnd(header, 5);
        System.out.println(node);
    }

    static class ListNode {

        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
